//
//  PublicMapVController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/14.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "PublicMapVController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
@import CoreLocation;
@import MapKit;

@interface PublicMapVController ()<MAMapViewDelegate,AMapSearchDelegate>
{
    MAMapView *_mapView;
    AMapSearchAPI  *_search;
    BOOL flag;
    
}
@property (nonatomic, strong)UIButton *rightBtn;
@property (nonatomic,retain) NSArray *pathPolylines;
@property (nonatomic,retain) MAUserLocation *currentLocation;



//本机地图
@property (nonatomic, strong) UIButton *btnSheet;

@property (nonatomic, strong) NSString *urlScheme;
@property (nonatomic, strong) NSString *appName;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;

@end

@implementation PublicMapVController
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (MAMapView *)mapView
{
    if (!_mapView) {
        _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
      [_mapView setZoomLevel:16 animated:YES];
        _mapView.delegate = self;
        _mapView.showsUserLocation = YES;    //YES 为打开定位，NO为关闭定位
        
        [_mapView setUserTrackingMode: MAUserTrackingModeFollow animated:NO]; //地图跟着位置移动
        
        //自定义定位经度圈样式
        _mapView.customizeUserLocationAccuracyCircleRepresentation = NO;
        _mapView.showsScale = NO;
        _mapView.showsCompass = NO;
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
        //恢复缩放比例和角度
   
        //后台定位
        _mapView.pausesLocationUpdatesAutomatically = NO;
        
       // _mapView.allowsBackgroundLocationUpdates = YES;//iOS9以上系统必须配置
        
    }
    return _mapView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    flag = YES;
    [self configureVC];
    
    [self addPoint];
}
- (void)addPoint{
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    pointAnnotation.coordinate = CLLocationCoordinate2DMake(30.2369970000,120.2525010000);
    pointAnnotation.title = @"商家名字";
    pointAnnotation.subtitle = @"我是商家的地址";
    [_mapView addAnnotation:pointAnnotation];
    
    

}


- (void)configureVC {
    [self.view insertSubview:self.mapView atIndex:0];
    
    //设置导航栏按钮的边距
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame= CGRectMake(0, 30, 50, 30);
    //[_rightBtn setImage:[UIImage imageNamed:@"fanhui"] forState:(UIControlStateNormal)];
    [_rightBtn addTarget:self action:@selector(onClickLeft) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:(UIControlStateNormal)];
    //[_rightBtn setBackgroundColor:[UIColor colorWithWhite:0.f alpha:0.5]];
    
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    [self.view addSubview:_rightBtn];
    
    
    
    UIButton *bacBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    bacBtn.frame = CGRectMake(15, kScreenHeight - 200, 40, 40);
    [bacBtn setImage:[UIImage imageNamed:@"dingwei22"] forState:(UIControlStateNormal)];
    [bacBtn addTarget:self action:@selector(handleBackYuanDian:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:bacBtn];
    
    
    
    
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, kScreen_Height - 140, kScreenWidth, 140)];
    bgV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgV];
    
    UILabel *labText = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, kScreenWidth, 20)];
    labText.text = @"商店的名字";
    labText.textColor = [UIColor blackColor];
    labText.font = kFont17;
    [bgV addSubview:labText];
    
    UILabel *labText2 = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(labText.frame)+5, kScreenWidth, 20)];
    labText2.text = @"商店的地址是什么呢";
    labText2.textColor = [UIColor lightGrayColor];
    labText2.font = kFont15;
    [bgV addSubview:labText2];
    
    
    
    UIButton *phoneMap = [UIButton buttonWithType:(UIButtonTypeCustom)];
    phoneMap.frame = CGRectMake(15, CGRectGetMaxY(labText2.frame)+15, kScreenWidth - 30, 45);
    [phoneMap setBackgroundImage:[UIImage imageNamed:@"bg1"] forState:(UIControlStateNormal)];
    [phoneMap setTitle:@"本机地图" forState:(UIControlStateNormal)];
    phoneMap.layer.masksToBounds = YES;
    phoneMap.layer.cornerRadius = 4;
    [phoneMap addTarget:self action:@selector(actionSheet) forControlEvents:(UIControlEventTouchUpInside)];
    [bgV addSubview:phoneMap];
    
    
    
}


- (void)onClickLeft {
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
   
    if (userLocation) {
        
        if (flag == YES) {
            self.currentLocation= userLocation;
            //绘制路线之前首先清楚之前规划的路线
            [MBProgressHUD showMessage:@"正在规划路线"];
            [self.mapView removeOverlays:self.mapView.overlays];
            //驾车路线规划
            _search = [[AMapSearchAPI alloc] init];
            _search.delegate = self;
            
            AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
            
            navi.requireExtension = YES;
            navi.strategy = 5;
            /* 出发点. */
            //30.241344,120.264888    //30.2369970000,120.2525010000
            navi.origin = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude
                                                   longitude:_currentLocation.coordinate.longitude];
            /* 目的地. */
            navi.destination = [AMapGeoPoint locationWithLatitude:30.2369970000
                                                        longitude:120.2525010000];
            [_search AMapDrivingRouteSearch:navi];
            flag = NO;
        }
    }
}

#pragma mark -- 定位位置发生改变



- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    /* 自定义userLocation对应的annotationView. */
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:userLocationStyleReuseIndetifier];
        }
        annotationView.image = [UIImage imageNamed:@"wodeweizhi"];
        return annotationView;
    }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        annotationView.image = [UIImage imageNamed:@"shangjia"];
        return annotationView;
    }
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    //通过AMapNavigationSearchResponse对象处理搜索结果
    //NSString *route = [NSString stringWithFormat:@"Navi: %@", response.route];
    
    AMapPath *path = response.route.paths[0]; //选择一条路径
    AMapStep *step = path.steps[0]; //这个路径上的导航路段数组
    NSLog(@"%@",step.polyline);   //此路段坐标点字符串
    
    if (response.count > 0)
    {
        //移除地图原本的遮盖
        [_mapView removeOverlays:_pathPolylines];
        _pathPolylines = nil;
        
        // 只显⽰示第⼀条 规划的路径
        _pathPolylines = [self polylinesForPath:response.route.paths[0]];
        NSLog(@"%@",response.route.paths[0]);
        //添加新的遮盖，然后会触发代理方法进行绘制
        [_mapView addOverlays:_pathPolylines];
    }

}


//路线解析
- (NSArray *)polylinesForPath:(AMapPath *)path
{
    if (path == nil || path.steps.count == 0)
    {
        return nil;
    }
    NSMutableArray *polylines = [NSMutableArray array];
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL *stop) {
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline
                                                         coordinateCount:&count
                                                              parseToken:@";"];
        
        
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        
        //          MAPolygon *polygon = [MAPolygon polygonWithCoordinates:coordinates count:count];
        
        [polylines addObject:polyline];
        free(coordinates), coordinates = NULL;
    }];
    return polylines;
}

//解析经纬度
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token
{
    if (string == nil)
    {
        return NULL;
    }
    
    if (token == nil)
    {
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","])
    {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }
    
    else
    {
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL)
    {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++)
    {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    
    
    return coordinates;
}
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    [MBProgressHUD hideHUD];
    NSLog(@"Error: %@", error);
}
//绘制遮盖时执行的代理方法
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    /* 自定义定位精度对应的MACircleView. */
    
    //画路线
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        [MBProgressHUD hideHUD];
        //初始化一个路线类型的view
        MAPolylineRenderer *polygonView = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        //设置线宽颜色等
        polygonView.lineWidth = 4.0f;
        polygonView.strokeColor = [UIColor colorWithRed:0.015 green:0.658 blue:0.986 alpha:1.000];
        polygonView.fillColor = [UIColor colorWithRed:0.940 green:0.771 blue:0.143 alpha:0.800];
        polygonView.lineJoinType = kMALineJoinRound;//连接类型
        //返回view，就进行了添加
        return polygonView;
    }
    return nil;
    
}



- (void)handleBackYuanDian:(UIButton *)sender  {
    
   
    [_mapView setCenterCoordinate: _currentLocation.coordinate animated:YES];
    //恢复缩放比例和角度
    [_mapView setZoomLevel:16 animated:YES];
    
    [_mapView setRotationDegree:0 animated:YES duration:0.5];
    [_mapView setCameraDegree:0 animated:YES duration:0.5];
    
   flag = YES;
    
}




//进入本机地图
- (void)handlePhoneMap {
    self.btnSheet = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.btnSheet.frame = CGRectMake(0, 0, 100, 50);
    self.btnSheet.center = self.view.center;
    [self.btnSheet setTitle:@"show sheet" forState:UIControlStateNormal];
    [self.btnSheet addTarget:self action:@selector(actionSheet) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.btnSheet];
    
    

    
}
- (void)actionSheet
{
    
    self.urlScheme = @"demoURI://";
    self.appName = @"demoURI";
    //目标的经纬度(由后台返给我们)
    self.coordinate = CLLocationCoordinate2DMake(30.2369970000,
                                                 120.2525010000);
    __block NSString *urlScheme = self.urlScheme;
    __block NSString *appName = self.appName;
    __block CLLocationCoordinate2D coordinate = self.coordinate;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择地图" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //这个判断其实是不需要的
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]])
    {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
            //目的地名称,可以传值进来,当然我们实际需要的并不是它,它只作为给用户的展示,我们实际需要的是self.coordinate,通过它来进行定位
            toLocation.name = @"我是商户的名字";
            [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                           launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
        }];
        
        [alert addAction:action];
    }
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]])
    {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=商店名字&mode=driving&coord_type=gcj02",coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }];
        
        [alert addAction:action];
    }
    
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]])
    {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",appName,urlScheme,coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }];
        
        [alert addAction:action];
    }
    
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]])
    {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"谷歌地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",appName,urlScheme,coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }];
        
        [alert addAction:action];
    }
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}


@end
